package com.jvm;

/**
 * @Author:zxh
 * @Description: 自定义类加载器,实现 打破双亲委派机制
 * @Date: 2021/3/6
 * @Modified By:
 */
public class MyClassLoaderTest2 {
    static class MyClassLoad extends ClassLoader {
        private String classpath;
/*
        public MyClassLoad(String classpath) {
            this.classpath = classpath;
        }

        private byte[] loadByte(String name) throws Exception {
            String str = null;
            str = name.replaceAll("\\.", "/");
            FileInputStream fis = new FileInputStream(classpath + "/" + str + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            try {
                byte[] bytes = loadByte(name);
                //defineClass 将一个字节数组转为Class对象，这个字节数组是class文件读取后最终的字节数组
                return defineClass(name, bytes, 0, bytes.length);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ClassNotFoundException();
            }
        }

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            synchronized (getClassLoadingLock(name)) {
                //检查当前类加载器是否已经加载了该类
                Class<?> c = findLoadedClass(name);
                if (c == null) {
                    long t1 = System.nanoTime();
                    //都会调用URLClassLoader的findClass方法在加载器的类路径里查找并加载该类
                    c = findClass(name);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }

        }
    }

    public static void main(String[] args) throws Exception {
        MyClassLoad myClassLoad = new MyClassLoad("D:/test");
        ////尝试用自己改写类加载机制去加载自己写的java.lang.String.class
        //Class<?> aClass = myClassLoad.loadClass("com.jvm.User1");
        Class<?> aClass = myClassLoad.loadClass("java.lang.String");
        Object newInstance = aClass.newInstance();
        Method method = aClass.getDeclaredMethod("toString", null);
        method.invoke(newInstance, null);
        System.out.println(aClass.getClassLoader().getClass().getName());

    }*/
    }
}
